# -*- coding: utf-8 -*-
from flask import jsonify
from app.api.v1.admin_api import admin_api_bp
from app.models import db
from app.models.activity import Activity, ActivityParticipant
from app.models.order import Order
from app.models.payment import Payment
from app.utils.decorators import admin_required
from app.utils.response import success, not_found, internal_server_error

@admin_api_bp.route('/activities/<int:activity_id>', methods=['DELETE'])
@admin_required
def delete_activity(activity_id):
    """
    删除一个活动及其所有相关数据
    ---
    tags:
      - 管理员接口 - 活动管理
    parameters:
      - in: path
        name: activity_id
        type: integer
        required: true
        description: 要删除的活动的ID
    security:
      - bearerAuth: []
    responses:
      200:
        description: 活动及相关数据删除成功
        schema:
          type: object
          properties:
            message:
              type: string
              example: Activity and all related data deleted successfully.
      404:
        description: 活动未找到
      500:
        description: 服务器内部错误
    """
    activity = Activity.query.get(activity_id)
    if not activity:
        return not_found('Activity not found.')

    try:
        # 查找所有关联的订单
        orders = Order.query.filter_by(activity_id=activity.id).all()
        order_ids = [order.id for order in orders]

        # 1. 删除与这些订单关联的所有支付记录
        if order_ids:
            Payment.query.filter(Payment.order_id.in_(order_ids)).delete(synchronize_session=False)

        # 2. 删除所有关联的订单
        if orders:
            Order.query.filter_by(activity_id=activity.id).delete(synchronize_session=False)

        # 3. 删除所有活动的参与者记录
        ActivityParticipant.query.filter_by(activity_id=activity.id).delete(synchronize_session=False)

        # 4. 删除活动本身
        db.session.delete(activity)

        # 提交事务
        db.session.commit()

        return success(message='Activity and all related data deleted successfully.')

    except Exception as e:
        db.session.rollback()
        # 可以在这里添加日志记录
        # current_app.logger.error(f"Error deleting activity {activity_id}: {e}")
        return internal_server_error('An error occurred while deleting the activity.') 